package com.fhc.base

import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.compose.LocalLifecycleOwner
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.ensureActive
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.launch
import timber.log.Timber


enum class EventType {
    UsbAttached, UsbDetached, UsbData, MockTest, AvgPer, RssiDataFrom,RestartApp, ClearAllData, Any, ToggleMockJob,
}

interface EventBusDataIF {

}

data class RssiDataFromDto(val rssiDataFrom: Long = System.currentTimeMillis()) : EventBusDataIF

class EventBusSubGInfo() : EventBusDataIF{
    var key: String = ""
    var channel: String = ""
    var port: String = ""
    var panId: String = ""
    var encryption: Boolean = false
    fun copy():EventBusSubGInfo{
        val copy = EventBusSubGInfo()
        copy.panId = panId
        copy.port = port
        copy.encryption = encryption
        copy.key = key
        copy.channel = channel
        return copy
    }
}
class EventMockMode() : EventBusDataIF{
    var mock: Boolean = false
}
data class FlowEventBusData(
    val dataType: EventType,
    val dataObj: EventBusDataIF? = null
)


/**
 * Fhc flow event bus
 *
 * @constructor Create empty Fhc flow event bus
 *     EventObserver(onCreate = {
 *         CoroutineScope(Dispatchers.Default).launch {
 *             FhcFlowEventBus.subscribe<FlowEventBusData> {event->
 *                 CoroutineScope(Dispatchers.Main).launch {
 *                     navActions.navigateToStart()
 *                     if(event.dataObj is EventDataTest){
 *                         Timber.i("TodoNavGraph  FlowEventBusData=    ${event.dataObj.firstName}  ${event.dataObj.lastName}")
 *                     }else if(event.dataObj is EventDataTest2){
 *                         Timber.i("TodoNavGraph  FlowEventBusData=    ${event.dataObj.aaa}   ${event.dataObj.bbb}")
 *                     }
 *                 }
 *             }
 *         }
 *     })
 */
object FhcFlowEventBus {
    private val mutableEvents = MutableSharedFlow<Any>()
    val events = mutableEvents.asSharedFlow()

    fun publish(event: Any) {
        CoroutineScope(Dispatchers.Default).launch {
            mutableEvents.emit(event)
        }
    }

    suspend inline fun <reified FlowEventBusData> subscribe(crossinline onEvent: (FlowEventBusData) ->Unit) {
        return events.filterIsInstance<FlowEventBusData>().collect {event ->
            currentCoroutineContext().ensureActive()
            onEvent(event)
        }
    }
}


@Composable
fun EventObserver(
    onPause: ()-> Unit = {},
    onResume: ()-> Unit = {},
    onCreate: ()-> Unit = {},
    onStop: ()-> Unit = {},
    onDestroy: ()-> Unit = {}
){

    // 1、获取当前LifecycleOwner（即Activity或Fragment）
    val lifecycleOwner = LocalLifecycleOwner.current
//        val lifecycleState by lifecycleOwner.lifecycle.currentStateFlow.collectAsState()
//        LaunchedEffect(lifecycleState) {
//            // Do something with your state
//            // You may want to use DisposableEffect or other alternatives
//            // instead of LaunchedEffect
//            when (lifecycleState) {
//                Lifecycle.State.DESTROYED -> {
//                    Timber.i("   >>>>>>DESTROYED")
//                }
//                Lifecycle.State.INITIALIZED -> {
//                    Timber.i("   >>>>>>INITIALIZED")}
//                Lifecycle.State.CREATED -> {
//                    Timber.i("   >>>>>>CREATED")}
//                Lifecycle.State.STARTED -> {
//                    Timber.i("   >>>>>>STARTED")}
//                Lifecycle.State.RESUMED -> {
//                    Timber.i("   >>>>>>RESUMED")}
//            }
//        }

    // 2、使用DisposableEffect来处理生命周期事件
    DisposableEffect(lifecycleOwner) {
        // 3.2实现的方法二：
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_CREATE -> {
                    onCreate()
                    Timber.i("   >>>>>>ON_CREATE")
                }

                Lifecycle.Event.ON_START -> {
                    Timber.i("   >>>>>>ON_START")}
                Lifecycle.Event.ON_RESUME -> {
                    onResume()
//                    CoroutineScope(Dispatchers.Default).launch {
//                        FhcFlowEventBus.subscribe<FlowEventBusData> {event->
//
//                            if(event.dataObj is EventDataTest){
//                                Timber.i("FlowEventBusData=    ${event.dataObj.firstName}  ${event.dataObj.lastName}")
//                            }else if(event.dataObj is EventDataTest2){
//                                Timber.i("FlowEventBusData=    ${event.dataObj.aaa}   ${event.dataObj.bbb}")
//                            }
//                        }
//                    }
                    Timber.i("   >>>>>>ON_RESUME")}
                Lifecycle.Event.ON_PAUSE -> {
                    onPause()
                    Timber.i("   >>>>>>ON_PAUSE")}
                Lifecycle.Event.ON_STOP -> {
                    onStop()
                    Timber.i("   >>>>>>ON_STOP")}
                Lifecycle.Event.ON_DESTROY -> {
                    onDestroy()
                    Timber.i("   >>>>>>ON_DESTROY")}
                else -> {
                    Timber.i("   >>>>>>elseelseelseelse")}
            }
        }
        // 3.2实现的方法二：
        lifecycleOwner.lifecycle.addObserver(observer)

        // 4、退离Composition时执行的清理操作
        onDispose {
            Timber.i("   >>>>>>onDispose")
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
}
